package demo3.boot.config;

import demo3.boot.pojo.User;
import demo3.boot.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
//     授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//取到下面的User对象
//        设置数据库的权限到shiro用户权限中
        info.addStringPermission(currentUser.getPerms());
        return info;
    }
//     认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证");
        UsernamePasswordToken userToken =  (UsernamePasswordToken) token;
//        未连接数据库的时候
//        String name = "root";
//        String password = "123456";
//        if(!userToken.getUsername().equals(name)){
//            return null; //抛出异常
//        }
        User user = userService.queryUserByName(userToken.getUsername());
        String name = user.getName();
        String password = user.getPassword();
        if ( user == null){
            return null;
        }
//        可以加密 MD5 MD5盐值加密
//        封装用户的登陆数据 密码认证,shiro做了加密
        return new SimpleAuthenticationInfo(user,password,"");//放入User对象
    }
}
